package cn.bdqn.sms.system.service.impl;

import cn.bdqn.sms.common.dto.LoginDTO;
import cn.bdqn.sms.system.entity.SysMenu;
import cn.bdqn.sms.system.entity.SysRoleMenu;
import cn.bdqn.sms.system.entity.SysUser;
import cn.bdqn.sms.system.entity.SysUserRole;
import cn.bdqn.sms.system.mapper.SysMenuMapper;
import cn.bdqn.sms.system.mapper.SysRoleMenuMapper;
import cn.bdqn.sms.system.mapper.SysUserMapper;
import cn.bdqn.sms.system.mapper.SysUserRoleMapper;
import cn.bdqn.sms.system.service.SysUserService;
import cn.bdqn.sms.system.vo.SysUserVO;
import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangpengxiang
 * @description 用户业务接口
 * @date 2024/11/18
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public SysUserVO login(LoginDTO loginDTO) {
        // 构建查询条件，先根据用户名查询用户
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, loginDTO.getUsername());
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);

        // 如果用户不存在，直接返回null
        if (sysUser == null) {
            return null;
        }

        // 对用户输入的密码进行BCrypt哈希验证，而不是直接比较明文
        boolean passwordMatch = BCrypt.checkpw(loginDTO.getPassword(), sysUser.getPassword());

        // 如果密码不匹配，返回null
        if (!passwordMatch) {
            return null;
        }

        // 将查询到的用户实体转换为视图对象并返回
        SysUserVO sysUserVO = BeanUtil.copyProperties(sysUser, SysUserVO.class);
        return sysUserVO;
    }

}
